#include "ByteBuffer.h"
#include <memory.h>

uint32 ByteBuffer::read(void *buf, uint32 len)
{
    if (len > this->avail()) len = this->avail();
    if ( len )
    {
        memcpy(buf, this->rd_ptr(), len);
        this->rd_ptr(len);
    }

    return len;
}

uint32 ByteBuffer::write(const void *buf, uint32 len)
{
    if (len > this->free())
    {
        if (_growth > 0)
        {
            do
            {
                _size += _growth;
            }
            while (len > this->free());

            this->resize( _size );
        }
        else
        {
            len = this->free();
            MCL_ASSERT(!"ByteBuffer full while writing data");
        }
    }

    if ( len )
    {
        memcpy(this->wr_ptr(), buf, len);
        this->wr_ptr(len);
    }

    return len;
}

ByteBuffer& ByteBuffer::operator >> (string &str)
{
    uint32 avail = this->avail();
    if ( avail )
    {
        // clear string
        if ( !str.empty() ) str.clear();

        // read string
        uint32 n = (uint32)strnlen(this->rd_ptr(), avail);
        str.append(this->rd_ptr(), n);

        if (n < avail)
        {
            this->rd_ptr(n + 1); // including terminating 0
        }
        else
        {
            this->rd_ptr(n);
        }
    }

    return *this;
}
